package com.hcloud.auth.api.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hcloud.common.core.base.HCloudResult;
import com.hcloud.common.core.constants.CoreContants;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author hepangui
 * @date 2018/10/12
 * 客户端异常处理
 */
@Slf4j
@Component
@AllArgsConstructor
public class HcloudResourceAuthExceptionEntryPoint implements AuthenticationEntryPoint {
    private final ObjectMapper objectMapper;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException {
        response.setCharacterEncoding(CoreContants.UTF8);
        response.setContentType(CoreContants.CONTENT_TYPE);
        HCloudResult hcloudResult = new HCloudResult("非法请求，请求拦截");
        hcloudResult.setCode(HCloudResult.NEEDLOGIN);
//        if (authException != null) {
//            result.setMsg("error");
//            result.setData(authException.getMessage());
//        }
//        response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        PrintWriter printWriter = response.getWriter();
        printWriter.append(objectMapper.writeValueAsString(hcloudResult));
    }
}
